<template>
  <GlobalBG
    title="工单"
    bannerText="轻松掌握工单动态，确保每个任务都能及时跟进！"
    bannerImage="image-3"
    bannerImageWidth="254rpx"
    bannerImageHeight="222rpx"
  >
    <view class="work-order-list">
      <view class="status-header">
        <text
          class="status-item"
          @click="changeTab(true)"
          :class="{ selected: activeTab }"
          >未处理（{{ unhandledCount }}）</text
        >
        <text
          class="status-item"
          @click="changeTab(false)"
          :class="{ selected: !activeTab }"
          >已处理</text
        >
        <!-- 已处理（{{ handledCount }}） -->
      </view>
      <view
        class="work-order-content"
        :style="{
          transform: activeTab ? 'translateX(0)' : 'translateX(-50%)',
        }"
      >
        <view>
          <view class="order-list">
            <view
              class="order-item"
              v-for="(item, index) in unhandledList"
              :key="index"
              @click="goToDetail(item.id)"
            >
              <text
                class="status-tag"
                :style="{ color: activeTab ? '#fca222' : '#8cf6bd' }"
                >{{ activeTab ? "待处理" : "已处理" }}</text
              >

              <view class="order-info">
                <view class="order-title">
                  {{ item.title }}
                </view>
                <view class="info-item">创建时间：{{ item.createTime }}</view>
                <view class="info-item">派发人：{{ item.sender }}</view>
              </view>
            </view>
          </view>
          <uni-load-more
            :color="
              unhandleLoadingStatus == 'more' ? '#007AFF' : 'rgb(119, 119, 119)'
            "
            :status="unhandleLoadingStatus"
            :contentText="{
              contentdown: '点击加载更多',
            }"
            @click="
              unhandleLoadingStatus == 'more'
                ? loadMoreData()
                : () => {
                    return false;
                  }
            "
          />
        </view>
        <view>
          <view class="order-list">
            <view
              class="order-item"
              v-for="(item, index) in handledList"
              :key="index"
              @click="goToDetail(item.id)"
            >
              <text
                class="status-tag"
                :style="{ color: activeTab ? '#fca222' : '#8cf6bd' }"
                >{{ activeTab ? "待处理" : "已处理" }}</text
              >

              <view class="order-info">
                <view class="order-title">
                  {{ item.title }}
                </view>
                <view class="info-item">创建时间：{{ item.createTime }}</view>
                <view class="info-item">派发人：{{ item.sender }}</view>
              </view>
            </view>
          </view>
          <uni-load-more
            :color="
              handleLoadingStatus == 'more' ? '#007AFF' : 'rgb(119, 119, 119)'
            "
            :status="handleLoadingStatus"
            :contentText="{
              contentdown: '点击加载更多',
            }"
            @click="
              handleLoadingStatus == 'more'
                ? loadMoreData()
                : () => {
                    return false;
                  }
            "
          />
        </view>
      </view>
    </view>
  </GlobalBG>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import api from "@/api/modules/home";

const activeTab = ref(true);
const changeTab = (flag: boolean) => {
  handleCurrPage.value = 1;
  unhandleCurrPage.value = 1;
  activeTab.value = flag;
};

const fetchDataByType = async (status, list, count, loading, currPage) => {
  try {
    const requestData = {
      page: currPage.value, // 示例页码
      pagesize: 10, // 示例每页数量
      status: status,
    };
    loading.value = "loading";
    let res = await api.getPageTbWorkOrder(requestData);
    console.log("获取工单列表", res);
    let currList: any = [];
    if (res.code === 0 && res.data && res.data.list) {
      res.data.list.forEach((alarm) => {
        currList.push({
          id: alarm.uuid,
          title: alarm.description || alarm.alarm_description,
          createTime: alarm.create_time,
          sender: alarm.create_name || "未知",
        });
      });
      count.value = res.data.total;
    }
    list.value = [...list.value, ...currList];
    currPage.value++;

    // 判断是否还有更多数据
    if (list.value.length >= count.value) {
      loading.value = "noMore";
    } else {
      loading.value = "more";
    }
    console.log(
      `更新后的 ${status === "已完成" ? "已处理" : "未处理"} 列表`,
      list.value
    );
  } catch (error) {
    console.error("请求失败:", error);
  }
};

// 合并后的函数
const getPageTbWorkOrder = async () => {
  // 调用函数获取未处理工单数据
  await fetchDataByType(
    "处理中",
    unhandledList,
    unhandledCount,
    unhandleLoadingStatus,
    unhandleCurrPage
  );
  // 调用函数获取已处理工单数据
  await fetchDataByType(
    "已完成",
    handledList,
    handledCount,
    handleLoadingStatus,
    handleCurrPage
  );
};

const unhandledList = ref<any[]>([]);
const handledList = ref<any[]>([]);

const handleLoadingStatus = ref("loading");
const unhandleLoadingStatus = ref("loading");

const handleCurrPage = ref(1);
const unhandleCurrPage = ref(1);

const unhandledCount = ref(0);
const handledCount = ref(0);
// 跳转详情页
const goToDetail = (id: string) => {
  uni.navigateTo({
    url: `/pages/work-order/detail?id=${id}`,
  });
};

const loadMoreData = async () => {
  if (activeTab.value) {
    // 调用函数获取未处理工单数据
    await fetchDataByType(
      "处理中",
      unhandledList,
      unhandledCount,
      unhandleLoadingStatus,
      unhandleCurrPage
    );
  } else {
    // 调用函数获取已处理工单数据
    await fetchDataByType(
      "已完成",
      handledList,
      handledCount,
      handleLoadingStatus,
      handleCurrPage
    );
  }
};

onMounted(async () => {
  Promise.all([getPageTbWorkOrder()]);
});
</script>

<style lang="scss" scoped>
.work-order-list {
  background-color: #f4f7ff;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  .header {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    color: white;

    .title {
      font-size: 20px;
      margin-bottom: 10px;
    }

    .illustration {
      width: 150px;
      height: 100px;
      margin-bottom: 10px;
    }

    .tips {
      font-size: 14px;
    }
  }
  .status-header {
    display: flex;
    justify-content: space-around;
    height: 97rpx;
    line-height: 97rpx;

    background: #ffffff;
    box-shadow: 0rpx 2rpx 20rpx 0rpx rgba(84, 93, 115, 0.13);
    .status-item {
      font-weight: 500;
      font-size: 28rpx;
      color: #333333;
      padding-left: 8rpx;
      &.selected {
        color: #3b7cff;
        border-bottom: 8rpx solid #3b7cff;
      }
    }
  }
  .work-order-content {
    flex: 1;
    overflow: auto;
    display: flex;
    width: 200%;
    transition: opacity 300ms, -webkit-transform 300ms, transform 300ms;
    & > uni-view {
      flex: 1;
      height: 100%;
      overflow: auto;
    }
  }
  .order-list {
    padding: 20rpx 20rpx 0 20rpx;

    .order-item {
      padding: 15px;
      margin-bottom: 20rpx;
      background: #ffffff;
      box-shadow: 0rpx 2rpx 20rpx 0rpx rgba(84, 93, 115, 0.13);
      border-radius: 20rpx;
      position: relative;
      &:last-child {
        margin-bottom: 0;
      }
      .status-tag {
        position: absolute;
        top: 0;
        right: 0;
        background: url("/static/images/icon-10.png") no-repeat;
        background-size: 100% 100%;
        width: 140rpx;
        height: 50rpx;
        text-align: center;
        line-height: 50rpx;
      }

      .order-info {
        .order-title {
          font-weight: 400;
          font-size: 28rpx;
          color: #333333;
          line-height: 40rpx;
        }
        .info-item {
          font-weight: 400;
          font-size: 26rpx;
          color: #999999;
          line-height: 37rpx;
          margin-top: 20rpx;
        }
      }
    }
  }
}
</style>
